/*网盘——服务端*/
#include "server.h"

int main(void)
{	
	int fd, newfd;
	int ret;
	char buf[50];//命令字符串
	
	/*买电话*/
	fd = socket(AF_INET, SOCK_STREAM, 0);
	if (fd == -1) 
	{
		perror("socket");
		exit(1);
	}
	//重用端口号
	int on = 1;
	setsockopt(fd,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on)); 

	/*绑定电话卡*/
	struct sockaddr_in server;
	server.sin_family = AF_INET;
	server.sin_addr.s_addr = inet_addr("192.168.104.99");
	server.sin_port = htons(12001);
	ret = bind(fd, (struct sockaddr *)&server, sizeof(server));
	if (ret == -1) 
	{
		perror("bind");
		exit(1);
	}
	
	/*监听*/
	listen(fd, 5); //不阻塞，最多接听5个
	printf("tcp server have started...\n");
	
	struct sockaddr_in client;//保存客户端的socket地址
	socklen_t len = sizeof(client);
	
	while (1) 
	{
		/*接听*/
		newfd = accept(fd, (struct sockaddr *)&client, &len);//没有连接请求就一直阻塞
		if (newfd == -1) 
		{
			perror("accept");
			exit(1);
		}
		printf("connect success with client...\n");
		printf("ip:%s\n", inet_ntoa(client.sin_addr));
		printf("port:%d\n", ntohs(client.sin_port));

		/*从客户端接收命令*/
		bzero(buf, 50);
		ret = read(newfd, buf, 50);
		if (ret < 0) 
		{
			perror("read");
			continue;
		}
		printf("recv command: %s", buf);//自带换行符
		
		if(strncmp(buf,"ls",2) == 0)
			do_ls(newfd);
		else if(strncmp(buf,"get",3) == 0)
			do_get(newfd,buf);
		else if(strncmp(buf,"put",3) == 0)
			do_put(newfd,buf);
	}
	
	/*挂电话*/
	close(fd);
	
	return 0;
}

